package com.cms.manage.filter;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Vector;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.*;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 增加过滤器
 * @author sgy 
 * OncePerRequestFilter:实现保证每个请求只走一次过滤器
 */
@WebFilter(filterName="uotationFilter",urlPatterns="/*")
public class QuotationFilter  implements Filter {


	/**
	 * 内部类 继承HttpServletRequestWrapper，创建装饰类，以达到修改HttpServletRequest参数的目的
	 * 重写几个HttpServletRequestWrapper中的方法
	 */
	private class QuotationWrapper extends HttpServletRequestWrapper {
		private Map<String, String[]> parameterMap; // 所有参数的Map集合
		public QuotationWrapper(HttpServletRequest request) {
			super(request);
			parameterMap = request.getParameterMap();
		}
		/**
		 * 获取所有参数名 使用Vector考虑到多线程场景
		 * @return 返回所有参数名
		 */
		@Override
		public Enumeration<String> getParameterNames() {
			Vector<String> vector = new Vector<String>(parameterMap.keySet());
			return vector.elements();
		}
		/**
		 * 获取指定参数名的值
		 * @param name指定参数名
		 * @return 指定参数名的值
		 */
		@Override
		public String getParameter(String name) {
			String[] results = parameterMap.get(name);
			if (results == null || results.length <= 0)
				return null;
			else {
				return modify(results[0]);
			}
		}
		/**
		 * 获取指定参数名的所有值的数组
		 */
		@Override
		public String[] getParameterValues(String name) {
			String[] results = parameterMap.get(name);
			if (results == null || results.length <= 0)
				return null;
			else {
				int length = results.length;
				for (int i = 0; i < length; i++) {
					results[i] = modify(results[i]);
				}
				return results;
			}
		}
		/**
		 * 定义请求参数过滤规则
		 * @param string原参数值
		 * @return 修改之后的值
		 */
		private String modify(String string) {
		   //如果请求参数为"",转成null,传入参数为"""",则不过滤。
			if ("".equals(string)) {
				string = null;
			}
			return string;
		}
	}
	/**
	 * 初始化过虑器
	 */
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		QuotationWrapper mParametersWrapper = new QuotationWrapper(request);
		filterChain.doFilter(mParametersWrapper, response);	
	}
	/**
	 * 初始化销毁
	 */
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}
